#include <stdio.h>

size_t my_strlen (const char * s)
{
    const char *p = s;

    while (*p++)
        ;
    return (p-s);
}

int my_strcmp (const char * s1, const char * s2)
{
    const char *p1 = s1, *p2 = s2;

    while (*p1 == *p2++) {
        if (*p1++ == '\0') {
            return 0;
        }
    }
    
    return (*(unsigned char*)p1 - *(unsigned char*)--p2);
}

char * my_strcpy (char * dest, const char * src)
{
    char *p = dest;

    if (dest == NULL || src == NULL) {
        return NULL;
    }

    while ((*dest++ = *src++) != '\0'); 

    return p;
}

char * my_strncpy(char * s1, const char * s2, unsigned n)
{
    char *p1 = s1;
    const char *p2 = s2;
    int i = 0;

    while ((i < n) && *p2) {
        *p1++ = *p2++;
        i++;
    }
    
    if (i < n) {
        *p1++ = '\0';
    }
    
    return s1;
}

char * my_strcat (char *s1, const char *s2)
{
    char *p1 = s1;
    const char *p2 = s2;

    for (; *p1; p1++);
    while (*p1++ = *p2++);
    return s1;
}

void* my_memcpy (void * dest, const void * src, size_t n)
{
    unsigned char *p1 = (unsigned char*)dest;
    unsigned char *p2 = (unsigned char*)src;

    while (n--) {
        *p1++ = *p2++;
    }

    return dest;
}

int main(int argc, char *argv[])
{
    int length;
    char str1[20] = "hello,";
    char str2[] = "zhoucheng";
    printf("build at %s, %s\n", __DATE__, __TIME__);

#if 0
    printf("str1=%s, str2=%s\n", str1, str2);
    length = my_strlen(str1);
    printf("length=%#x\n", length);
    

    printf("str1 %d str2\n", my_strcmp(str1, str2));

    printf("str1=%s\n", my_strncpy(str1, str2, my_strlen(str2)));
    printf("str1=%s, str2=%s\n", str1, str2);
    printf("strcat: %s\n", my_strcat(str1, str2));
#endif
    my_memcpy(str1, str2, my_strlen(str2));
    printf("str1=%s, str2=%s\n", str1, str2);
    
    return 0;
}

